//
//  AuthenticateViewController.swift
//  EasyDana
//
//  Created by mac on 2024/10/15.
//

import UIKit
import RxSwift
import RxCocoa
class AuthenticateViewController: UIViewController {

    private let bag = DisposeBag()
    
    var product_id = ""//产品ID
    
    var naviTitle: String = ""
    
    var step: Int = -1
    
    var totalStep = 0
    
    var getApi: Api!
    
    var saveApi: Api!
    
    var riskType = -1
    
    var beginDate = Date()
    
    private let source: BehaviorRelay<[BehaviorRelay<AuthenItemModel>]> = BehaviorRelay(value: [])
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.configView()
    }
    
    private func stepView(currentStep: Int, totalStep: Int)->UIView {
        let view = UIStackView()
        view.axis = .horizontal
        view.distribution = .fill
        view.alignment = .center
        func genStepDot(step: Int, done: Bool) -> UIView {
            let stepView = UIView()
            var image: String = "authen_complete"
            if (!done) {
                image = "authen_not_complete"
            }
            let imageView = UIImageView(image: UIImage(named: image))
            stepView.addSubview(imageView)
            imageView.snp.makeConstraints { make in
                make.edges.equalToSuperview()
                make.width.height.equalTo(32)
            }
            let nameLabel = UILabel()
            stepView.addSubview(nameLabel)
            nameLabel.text = "\(step)"
            nameLabel.textColor = UIColor.white
            nameLabel.font = UIFont.systemFont(ofSize: 16)
            nameLabel.snp.makeConstraints { make in
                make.center.equalToSuperview()
            }
            return stepView
        }
        func genLine(done: Bool) -> UIImageView {
            if (done) {
                return UIImageView(image: UIImage(named: "authen_complete_line"))
            } else {
                return UIImageView(image: UIImage(named: "authen_not_complete_line"))
            }
        }
        for i in 1 ... totalStep {
            if i <= currentStep {
                let dotView = genStepDot(step: i, done: true)
                view.addArrangedSubview(dotView)
            } else {
                let dotView = genStepDot(step: i, done: false)
                view.addArrangedSubview(dotView)
            }
            if (i != totalStep) {
                let lineView = genLine(done: i < currentStep)
                view.addArrangedSubview(lineView)
            }
        }
        return view
    }
    
    private func configView() {
        self.view.backgroundColor = UIColor.white//UIColor.hex(with: "#F7F7F7")
        let topView = UIView()
        self.view.addSubview(topView)
        let naviBar = NavigationBar()
        naviBar.title = naviTitle
        naviBar.titleColor = UIColor.hex(with: "#121001")
        naviBar.backColor = UIColor.hex(with: "#121001")
        self.view.addSubview(naviBar)
        naviBar.backClicked
            .subscribe(onNext: { [weak self] in
                self?.navigationController?.popViewController(animated: true)
            })
            .disposed(by: self.bag)
        naviBar.snp.makeConstraints { make in
            make.top.equalTo(self.view.snp.topMargin)
            make.left.right.equalToSuperview()
            make.height.equalTo(47)
        }
        let stepView = self.stepView(currentStep: self.step, totalStep: self.totalStep)
        self.view.addSubview(stepView)
        stepView.snp.makeConstraints { make in
            make.top.equalTo(naviBar.snp.bottom).offset(15)
            make.centerX.equalToSuperview()
        }
        let contentView = UIView()
        self.view.addSubview(contentView)
        contentView.backgroundColor = UIColor.hex(with: "#f7f7f7")
        contentView.snp.makeConstraints { make in
            make.left.bottom.right.equalToSuperview()
            make.top.equalTo(stepView.snp.bottom).offset(15)
        }
        let nextButton = UIButton(type: .system)
        nextButton.setImage(UIImage(named: "authen_next_step")?.withRenderingMode(.alwaysOriginal), for: .normal)
        contentView.addSubview(nextButton)
        nextButton.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(contentView.snp.bottomMargin).offset(-10)
        }
        nextButton.addTarget(self, action: #selector(nextAction(button:)), for: .touchUpInside)
        let scrollView = UIScrollView()
        scrollView.backgroundColor = contentView.backgroundColor
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        contentView.addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.bottom.equalTo(nextButton.snp.top).offset(-10)
        }
        let tipView = UIImageView(image: UIImage(named: "authen_tip"))
        scrollView.addSubview(tipView)
        tipView.snp.makeConstraints { make in
            make.left.top.equalToSuperview().offset(15)
        }
        let tableBGView = UIView()
        tableBGView.backgroundColor = UIColor.white
        scrollView.addSubview(tableBGView)
        tableBGView.layer.masksToBounds = true
        tableBGView.layer.cornerRadius = 14
        tableBGView.layer.shadowColor = UIColor.black.cgColor
        tableBGView.layer.shadowOpacity = 0.1
        tableBGView.snp.makeConstraints { make in
            make.top.equalTo(tipView.snp.bottom).offset(15)
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.left.equalTo(contentView).offset(15)
            make.right.equalTo(contentView).offset(-15)
            make.bottom.equalToSuperview().offset(-15)
        }
        let stackBGView = UIView()
        tableBGView.addSubview(stackBGView)
        stackBGView.backgroundColor = UIColor.color(with: 7, green: 7, blue: 7, alpha: 0.05)
        stackBGView.snp.makeConstraints { make in
            make.top.left.equalToSuperview().offset(15)
            make.right.bottom.equalToSuperview().offset(-15)
        }
        let stackView = UIStackView()
        stackBGView.addSubview(stackView)
        stackView.axis = .vertical
        stackView.spacing = 1
        stackView.alignment = .fill
        stackView.distribution = .fillEqually
        stackView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        self.source
            .observe(on: MainScheduler.instance)
            .map { models in
                return models.map { model in
                    let view = AuthenItemView(model: model)
                    return view
                }
            }
            .subscribe(onNext: { views in
                let arrangedViews = stackView.arrangedSubviews
                arrangedViews.forEach({$0.removeFromSuperview()})
                views.forEach({stackView.addArrangedSubview($0)})
            })
            .disposed(by: self.bag)
        self.source.observe(on: MainScheduler.instance)
            .map { list in
                return list.count * 75
            }
            .subscribe(onNext: { height in
                stackView.snp.remakeConstraints { make in
                    make.edges.equalToSuperview()
                    make.height.equalTo(height)
                }
            })
            .disposed(by: self.bag)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.getData()
    }
    
    @objc private func nextAction(button: UIButton) {
        switch self.saveApi {
        case .saveCardInfo:
            let confirmVC = BankCardConfirmViewController()
            let cardNo = self.source.value.filter({$0.value.openly == "cardNo"}).first!
            confirmVC.bankCardNo.accept(cardNo.value.foolishly)
            confirmVC.bankCardNo
                .withLatestFrom(cardNo) { cardNumber, element in
                    var ele = element
                    ele.foolishly = cardNumber
                    return ele
                }
                .bind(to: cardNo)
                .disposed(by: self.bag)
            self.alert(viewController: confirmVC)
            confirmVC.confirm
                .subscribe(onNext: { [weak self] _ in
                    self?.doUpload()
                })
                .disposed(by: self.bag)
            break
        default:
            self.doUpload()
            break
        }
    }
    
    private func doUpload() {
        Task {
            do {
                self.showLoading(text: nil)
                var param: [String: Any] = ["guns": self.product_id]
                self.source.value.forEach { model in
                    let key = model.value.openly
                    let tombs = model.value.tombs
                    var value = ""
                    switch tombs {
                    case "dead":
                        //选择
                        if let v  = model.value.cordially {
                            value = v
                        } else {
                            value = ""
                        }
                        break
                    default:
                        value = model.value.foolishly
                        break
                    }
                    param[key] = value
                }
                let res = try await HTTPManager.default.post(path: self.saveApi, param: param, dataType: [Int].self)
                if (res.code == 0) {
                    UploadStasticManager.default.uploadRiskPoint(type: self.riskType, beginTime: self.beginDate)
                    self.hideLoading()
                    self.navigationController?.popViewController(animated: true)
                } else {
                    self.hideLoading()
                    self.show(toast: res.state)
                }
            } catch {
                self.hideLoading()
            }
        }
    }
    
    private func getData() {
        Task {
            struct AuthenticateModel: Codable {
                let axe: [AuthenItemModel]
            }
            do {
                self.showLoading(text: nil)
                let res = try await HTTPManager.default.post(path: self.getApi, param: ["guns": self.product_id], dataType: AuthenticateModel.self)
                self.hideLoading()
                if res.code == 0 {
                    let src = res.data!.axe.map { model in
                        return BehaviorRelay(value: model)
                    }
                    self.source.accept(src)
                } else {
                    self.show(toast: res.state)
                }
            } catch {
                print(error)
                self.hideLoading()
                
            }
        }
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
